<template>
  <section>
    <!--工具栏：关键字查询 + 添加-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <!-- disabled：禁用按钮 -->
          <el-button type="primary" disabled @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData">导出数据</el-button>
        </el-form-item>
        <el-form-item>
          <!-- 默认name="file" -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/shop/importExcel"
                     list-type="text">
            <el-button type="warning">导入数据</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表：分页查询 -->
    <el-table :data="shops" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="50">
      </el-table-column>
      <el-table-column align="center" prop="name" label="店铺名称" width="120">
      </el-table-column>
      <el-table-column align="center" prop="tel" label="联系号码" width="150">
      </el-table-column>
      <el-table-column align="center" prop="registerTime" label="入驻时间" width="180">
      </el-table-column>
      <el-table-column align="center" label="状态" width="120" sortable>
        <template scope="scope">
          <span style="color: darkturquoise" v-if="scope.row.state==1">待审核</span>
          <span style="color: pink" v-if="scope.row.state==2">审核通过待激活</span>
          <span style="color: #13ce66" v-if="scope.row.state==3">激活成功</span>
          <span style="color: #ff4949" v-if="scope.row.state==4">驳回</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="address" :show-overflow-tooltip="true" label="店铺地址" width="130">
      </el-table-column>
      <el-table-column align="center" prop="logo" label="店铺Logo" width="150">
        <template scope="scope">
          <img :src="imgPrefix+scope.row.logo" width="50px">
        </template>
      </el-table-column>
      <el-table-column align="center" prop="admin.username" label="店长" width="130">
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template scope="scope">
          <el-button size="small" disabled @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" disabled size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button size="small" type="warning" @click="handleAudit(scope.$index, scope.row)">店铺审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具栏：批量删除 + 分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>
    <!--
       el-dialog - 对话框
          :title="title" - 标题
          :visible.sync="saveFormVisible" - 控制对话框是都显示，默认为false。点击添加或修改时改成true，就可以显示对话框了
          :close-on-click-modal="false" - 点对话框外不关闭对话框
      el-form - 表单
          :model="saveForm" - 表单数据/模型数据
          label-width="80px" - 标签的宽度
          :rules="saveFormRules" - 表单项验证
          ref="saveForm" - 表单验证，只有表单项每一项都通过，才能提交数据
      el-form-item - 表单项
          label="部门名称" - 标签
          prop="name" - 需要验证就要写prop
    -->
    <!--添加或编辑对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="店铺名称" prop="name" style="width: 320px">
          <el-input v-model="saveForm.name"></el-input>
        </el-form-item>
        <el-form-item label="联系号码" prop="tel" style="width: 320px">
          <el-input v-model="saveForm.tel"></el-input>
        </el-form-item>
        <el-form-item label="店铺地址" prop="address" style="width: 450px">
          <el-input v-model="saveForm.address"></el-input>
        </el-form-item>
        <el-form-item label="店铺Logo">
          <el-upload
              class="upload-demo"
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <!--
          回显机制【修改】：先定位（找到回显哪一个对象）再显示
            1.通过（v-model="saveForm.manager_id"）的manager_id去（v-for="item in managers"）的item中去找，找到回显哪一个对象
            2.对象中有很多属性值。再通过（:label="item.username"）回显对象的username属性值
          传值机制【添加和修改】
            1.当选中某一个经理时
            2.将这个经理的（:value="item.id"）id，传递给（v-model="saveForm.manager_id" ）manager_id，传给后端操作数据库
        -->
        <el-form-item label="店长">
          <el-select v-model="saveForm.admin_id" placeholder="请选择">
            <el-option v-for="item in employees"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 15px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

    <!-- 审核模态框 -->
    <el-dialog title="审核店铺" :visible.sync="shopAuditVisible" :close-on-click-modal="false">
      <el-form :model="shopAuditLog" label-width="80px"  ref="shopAuditLogForm">
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="shopAuditLog.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="shopAuditVisible = false">取消</el-button>
        <el-button type="primary" @click.native="auditPass">通过</el-button>
        <el-button type="primary" @click.native="auditReject">驳回</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
export default {
  data() {
    return {
      //列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",

      //1.分页查询的相关数据
      shops: [],    //列表数据
      listLoading: false, //列表的加载框
      pageSize: 5,        //每页显示条数
      currentPage: 1,     //当前页
      totals: 0,          //总条数

      //2.高级查询相关数据
      keyword: '',

      //3.批量删除的相关数据
      sels: [],//列表选中列


      //4.添加或修改的相关数据
      title: '',          //标题
      saveFormVisible: false,//控制对话框是都显示，默认为false
      saveLoading: false, //加载框
      saveFormRules: { // 表单项验证
        name: [
          {required: true, message: '请输入店铺名称', trigger: 'blur'}
        ],
        tel: [
          {required: true, message: '请输入联系号码', trigger: 'blur'}
        ],
        address: [
          {required: true, message: '请输入店铺地址', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        tel: "",
        address: "",
        logo: null,
        admin_id: null
      },

      //店长们
      employees: [],

      //审核模态框
      shopAuditVisible: false,
      //编辑界面数据
      shopAuditLog: {
        shopId: null,
        note:'',
      },
    }
  },
  methods: {

    exportData(){
      //不是asiox请求，所以需要加上http://localhost:8080
      location.href="http://localhost:8080/shop/export";
    },

    //1.分页查询 - 获取部门列表
    getShops() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;//显示加载框
      this.$http.post("/shop",para).then(res=>{
        //注意：res.data是axios获取响应数据的固定语法，这个实际就是PageList对象
        this.shops = res.data.data;//显示当前页分页数据
        this.totals = res.data.totals;//计算分页栏
        this.listLoading = false;//关闭加载框
      }).catch(res=>{
        this.$message.error("系统繁忙，请稍后重试!!!【400,404】")
      })
    },

    //2.点击分页实现
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getShops();
    },

    //3.关键字查询
    keywordQuery(){
      //假如当前页不在第一页，防止高级查询没有那么多页的时候出现空数据的问题
      this.currentPage = 1;
      this.getShops();
    },

    //4.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点确认框的确认按钮
        this.listLoading = true;
        this.$http.delete("/shop/"+row.id).then(res=>{
          if(res.data.success){
            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.totals/this.pageSize);
            //当删除最后一页的最后一条数据，并且不是第一页，就让当前页-1
            if(this.currentPage==totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage = this.currentPage - 1;
            }

            //方式二：
            /*if(this.shops.length==1 && this.currentPage!=1){
              this.currentPage = this.currentPage - 1;
            }*/

            this.getShops();
            this.$message.success("删除成功！");
          }else{
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => { //点取消
      });
    },

    //5.选项改变时触发
    selsChange: function (sels) {
      //将选中的所有对象【集合】赋值给模型数据sels
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      //获取选中对象的id
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/shop",ids).then(res=>{
          if(res.data.success){

            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.totals/this.pageSize);
            //当删除最后一页的所有数据，并且不是第一页，就让当前页-1
            if(this.currentPage==totalPage && (this.totals-this.sels.length)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage = this.currentPage - 1;
            }

            this.getShops();
            this.$message.success("删除成功！");
          }else{
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });
    },

    //7.显示编辑界面
    handleEdit: function (index, row) {
      this.title = " 编 辑 "
      //防止多个引用指向同一个对象
      this.saveForm = Object.assign({}, row);
      //显示对话框
      this.saveFormVisible = true;
      this.getEmployees();
    },
    //8.显示新增界面
    handleAdd: function () {
      this.title = " 新 增 "
      //重置
      this.saveForm = {
        id: null,
        tel: "",
        address: "",
        logo: null,
        admin_id: null
      };
      this.getEmployees();
      this.saveFormVisible = true;
    },
    //9.提交数据
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {//表单验证
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            this.$message.success("操作成功！");
            this.$http.put("/shop",this.saveForm).then(res=>{
              if(res.data.success){
                this.getShops();
              }else{
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.saveLoading = false; //关闭加载框
              this.saveFormVisible = false;//关闭对话框
            }).catch(res=>{
              this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
            })
          });
        }
      });
    },

    //获取所有的店长们
    getEmployees(){
      this.$http.get("/employee").then(res=>{
        this.employees = res.data;
      });
    },

    //点击店铺审核弹出模态框
    handleAudit: function (index, row) {
      this.shopAuditLog.shopId = row.id;
      this.shopAuditLog.note = '';
      this.shopAuditVisible = true;
    },

    //审核驳回
    auditReject(){
      this.$http.post("/shop/audit/reject",this.shopAuditLog).then(res=>{
        if(res.data.success){
          this.$message({
            message: '驳回成功',
            type: 'success'
          });
        }else{
          this.$message({
            message: '驳回失败',
            type: 'error'
          });
        }
        this.shopAuditVisible = false;
        this.getShops();
      })
    },
    //审核通过
    auditPass(){
      this.$http.post("/shop/audit/pass",this.shopAuditLog)
          .then(result=>{
            result = result.data;
            if(result.success){
              this.$message({
                message: '审核通过',
                type: 'success'
              });
            }else{
              this.$message({
                message: '审核失败',
                type: 'error'
              });
            }
            this.shopAuditVisible = false;
            this.getShops();
          })
    },

  },
  mounted() {
    this.getShops();
  }
}

</script>

<style scoped>
</style>